
var phantom = require("phantom");

var url = "https://detail.tmall.com/item.htm?spm=a222r.8253674.5749379772.2.488008eEN2idQ&acm=lb-zebra-204829-2429454.1003.4.2127445&id=557156077822&scm=1003.4.lb-zebra-204829-2429454.ITEM_557156077822_2127445&sku_properties=10004:900640275;5919063:6536025";


var priceEval = function () {
    var obj = {
        tagPrice: '',
        price: '',
        happyPrice: '',
        monthSellAmount: '',
        star: '',
        brandName: '',
        sku: '',
        attr: ''
    };

    var price1 = document.querySelector('#detail .tb-property .tm-fcs-panel .tm-tagPrice-panel .tm-price').innerHTML;

    var price2 = document.querySelector('#detail .tb-property .tm-fcs-panel #J_PromoPrice .tm-price').innerHTML;

    var price3 = document.querySelector('#detail .tb-property .tm-fcs-panel .tm-happy11-panel .tm-price').innerHTML;

    obj.tagPrice = price1;
    obj.price = price2;
    obj.happyPrice = price3;


    obj.monthSellAmount = document.querySelector('#detail .tb-property .tm-ind-panel .tm-ind-sellCount .tm-count').innerHTML;

    obj.star = document.querySelector('#detail .tb-property .tm-ind-panel .tm-ind-reviewCount .tm-count').innerHTML;

    // obj.sku = document.querySelector('#detail .tb-property .tb-key .tb-sku').innerHTML;

    try {
        obj.brandName = document.querySelector('#bd #attributes #J_BrandAttr .J_EbrandLogo').innerHTML;
    } catch (e) {
        obj.brandName = '';
    }


    // obj.attr = document.querySelector('#bd #attributes #J_AttrUL').innerHTML;

    return obj;

};

spider(url,console.log);

function startConnect() {
    return phantom.create().then(function (ph) {
        _ph = ph;
        return _ph.createPage();
    });
}

function endConnect(_page){
    _page.close().then(function () {
        _ph.exit();
    });
}

var _ph;
var _page;
var webpage;

function spider(_url,callback) {
    var timeStart = new Date().getTime();
    // phantom.create().then(function (ph) {
    //     _ph = ph;
    //     return _ph.createPage();
    // })


    if(!webpage){
        webpage = startConnect();
    }

    webpage.then(function (page) {
        _page = page;

        return _page.open(_url);
    }).then(function (status) {
        console.log(status);
        var time2 = new Date().getTime() - timeStart;
        console.log('use time1:' + time2);

        var priceObj;

        _page.evaluate(priceEval).then(function (obj) {

            priceObj = obj;

            var time = new Date().getTime() - timeStart;
            console.log(JSON.stringify(obj));
            console.log('use time:' + time);

            callback(priceObj);
            endConnect(_page);
           
        });


    }).catch(function (e) {
        console.log(e);
        _ph.exit();
    });
}



module.exports = spider;